package com.asit.demo.config;



import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
@Slf4j
public class AdminServiceCglibProxy implements MethodInterceptor {

    private Object target;

    public AdminServiceCglibProxy(Object target) {
        this.target = target;
    }

    //给目标对象创建一个代理对象
    public Object getProxyInstance() {
        //工具类
        Enhancer en = new Enhancer();
        //设置父类
        en.setSuperclass(target.getClass());
        //设置回调函数
        en.setCallback(this);
        //创建子类代理对象
        return en.create();
    }

    public Object intercept(Object object, Method method, Object[] arg2, MethodProxy proxy) throws Throwable {
        DynamicDataSourceContextHolder.push("salve1");//数据源名称
        Object obj=null;
        try {
            // your code 需注意使用后一定要使用poll清空数据源，
            log.info("代理开始");
            obj = method.invoke(target);
            log.info("代理结束");
        } catch (Exception e) {
            log.error("{}",e);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
        return obj;
    }


}
